package org.test.client.ui.component.panel;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

import org.test.client.ui.util.UIUtil;
import org.test.client.ui.util.run.RunCallBack;

public abstract class FadePanel extends JPanel{

	public float alpha = 1.0f;
	public boolean fadingFlag = false;
	//此标志 是用来 设置面板 是否 需要绘制 最上面一层 效果
	public boolean mask = false;
	
	public FadePanel(){
		
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		if(fadingFlag || mask){
			Graphics2D g2d = (Graphics2D) g;
			AlphaComposite srcOverAC = UIUtil.getSrcOverAC(alpha);
			g2d.setComposite(srcOverAC);
			g2d.setColor(this.getParent().getBackground());
			g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
		}
	}
	
	public void fadeOut(RunCallBack callBack){
		FadePanelRun run = new FadePanelRun(this, callBack);
		new Thread(run).start();
	}
	
	public void fadeIn(RunCallBack callBack){
		FadePanelRun run = new FadePanelRun(this,false, callBack);
		new Thread(run).start();
	}
	
}

class FadePanelRun implements Runnable {
	FadePanel comp;
	int frames = 40;
	int interval = 15;
	boolean fadeOut = true;
	RunCallBack callBack = null;
	
	public FadePanelRun(FadePanel comp, RunCallBack callBack){
		this.comp = comp;
		this.callBack = callBack;
	}
	
	public FadePanelRun(FadePanel comp,boolean fadeOut,RunCallBack callBack){
		this.comp = comp;
		this.fadeOut = fadeOut;
		this.callBack = callBack;
	}
	
	@Override
	public void run() {
		comp.fadingFlag = true;
		float avg = 1f / frames;
		if (fadeOut) {
//			comp.removeAll();
			comp.alpha = 0;
			for (int i = 0; i < frames; i++) {
				comp.alpha += avg;
				if(comp.alpha > 1){
					comp.alpha = 1;
				}
				comp.repaint();
				try {
					Thread.sleep(interval);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			comp.alpha = 1;
		} else {
			comp.alpha = 1;
			for (int i = 0; i < frames; i++) {
				comp.alpha -= avg;
				if(comp.alpha < 0){
					comp.alpha = 0;
				}
				comp.repaint();
				try {
					Thread.sleep(interval);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			//淡入 时 需要将 alpah 置0
			if(comp.alpha != 0){
				comp.alpha = 0;
				comp.repaint();
			}
		}
		if(callBack!=null){
			callBack.doAfterRun(comp);
		}
		
		comp.fadingFlag = false;
	}
	
}
